package tingshu.servlet.album;

import lombok.SneakyThrows;
import tingshu.repository.AlbumRepo;
import tingshu.util.DBUtil;
import tingshu.util.Log;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 发布专辑
 * @author houdaiqin
 * @date 2022/07/18 22:32
 **/
@WebServlet("/studio/album/publish.do")
public class PublishDoServlet extends HttpServlet {
    private final AlbumRepo albumRepo=new AlbumRepo();
    @Override
    @SneakyThrows
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aid = req.getParameter("aid");
        int newAid=Integer.parseInt(aid);
        UserVO currentUser=null;
        HttpSession session= req.getSession(false);
        if (session!=null){
            currentUser=(UserVO) session.getAttribute("currentUser");
        }
        if (currentUser==null){
            Log.println("用户未登录");
            return;
        }
        int uid= albumRepo.selectUidByAid(newAid);

        //1.验证当前登录用户是该专辑的主人
        if (uid!=currentUser.uid){
            Log.println("该专辑不属于此用户");
            return;
        }else {
            //2.更新专辑状态
            try (Connection c = DBUtil.connection()) {
                String sql = "update albums set state = 2 where aid = ?";
                try (PreparedStatement ps = c.prepareStatement(sql)) {
                    ps.setInt(1, newAid);

                    ps.executeUpdate();
                }
            }
        }
        //3.重定向到专辑列表页
        resp.sendRedirect("/studio/album/list.html");
    }
}